package com.yzy.fly.service.util;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.yzy.fly.entity.core.FlySql;
import com.yzy.fly.entity.role.*;
import com.yzy.fly.enums.IBaseEnum2;
import com.yzy.fly.type.SQLType;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import java.util.List;
import java.util.Map;

public class FlyMapperJavaFileUtil {
    //TODO
    public static String javaFile(FlyComponent flyComponent) {

        List<FlySql> flySqls = flyComponent.getFlySqls() ;
//
        List<String> importClassList = Lists.newArrayList();
        StringBuffer classFile = new StringBuffer("");


        StringBuffer packageBuffer = new StringBuffer("");
        StringBuffer importBuffer = new StringBuffer("");
        StringBuffer classBuffer = new StringBuffer("");

//        String name = (flyClass.getPackageName()+"."+flyClass.getClassName()).replace(".","/");
        //"com/yzy/bi/entity/core/Test"
//        String superName = flyClass.getSuperName();
//        if ("java.lang.Object".equals(superName)) {
//            superName = "";
//        }

//        if (StringUtils.isNotBlank(superName)) {
//            superName = superName.replace(".","/");
//            classBuffer.append(" extends").append(superName);
//        }

        String[] interfaces = new String[]{"java/io/Serializable" };

        //package
        packageBuffer.append("package ").append(flyComponent.getPackageName()).append(";").append("\n");
//        import
//        classFile.append("import ").append(model.getPackage()).append("\n");
        //class
        classBuffer.append("@Mapper").append("\n");

//        FlyTable table = model.getTable();
        List<FlyTableColumn> columns = null;
//        if (table != null) {
//            String tableName = table.getName();
//            classBuffer.append("@TableName(\""+tableName+"\")").append("\n");
//            columns = table.getColumns();
//        }

        classBuffer.append("public class ").append(flyComponent.getFileName());
//
//        //superClass
//
//        //interface
//
//
        classBuffer.append(" {");
        classBuffer.append("\n");
//        //field
//        List<FlyAttribute> attrs = model.getAttrs();

        if (CollectionUtils.isNotEmpty(flySqls)) {
            int flySqlSize = flySqls.size();
            for (int i = 0; i < flySqlSize; i++) {
                FlySql flySql =  flySqls.get(i);
                String sqlContent = flySql.getSqlContent();
                String type = flySql.getType();

                SQLType sqlType = IBaseEnum2.getByCustomWithCode(SQLType.class, type, (key1, key2) -> key1.equalsIgnoreCase(key2));
//                SQLType sqlType = IBaseEnum2.getByCode(SQLType.class, type);
                String annotationType = sqlType.getValue();

                boolean multiLine = false;
                if (sqlContent.contains("\n")) {
                    multiLine = true;
                }
                if (StringUtils.isNotBlank(annotationType)) {
                    if (SQLType.CALLABLE == sqlType) {
                        classBuffer.append("     ").append("@").append("Select");
//                      @Select(" call splitJSONArray_count(#{batchNo},#{key},#{absoluteKey})")
//                      @Options(statementType = StatementType.CALLABLE)
                    } else {
                        classBuffer.append("     ").append("@").append(annotationType);
                    }

                    if (!multiLine) {
                        classBuffer.append("(\"").append(sqlContent).append("\")").append("\n");
                    } else {
                        classBuffer.append("({\"\",").append("\n");
                        String[] split = sqlContent.split("\\n", -1);
                        for (int j = 0; j < split.length; j++) {
                            String subSql = split[j];
                            classBuffer.append("     \"").append(subSql).append("\",").append("\n");
                        }
                        classBuffer.append("     ").append("\"\"})").append("\n");
                    }
                    if (SQLType.CALLABLE == sqlType) {
                        classBuffer.append("     ").append("@Options(statementType = StatementType.CALLABLE)").append("\n");
                    }
                }

                String sqlId = flySql.getSqlId();
                //method
                String returnClass = flySql.getReturnClass();
                if (StringUtils.isBlank(returnClass)) {
                    returnClass = "void";
                }
                classBuffer.append("     ").append(returnClass).append(" ").append(sqlId).append("(");

                JSONArray params = flySql.getParams();
                //{"id": 49916, "name": "123", "type": "", "label": "213", "javaType": "1231", "jdbcType": "123"}

                if (CollectionUtils.isNotEmpty(params)) {
                    int paramsSize = params.size();
                    for (int j = 0; j < paramsSize; j++) {
                        JSONObject param =  params.getJSONObject(j);
                        String javaType = param.getString("javaType");
                        String name = param.getString("name");
                        classBuffer.append(javaType).append(" ").append(name);
                        if (j != paramsSize -1) {
                            classBuffer.append(",");
                        }
                    }
                }
                classBuffer.append(");");
                if(i != flySqlSize - 1){
                    classBuffer.append("\n").append("\n");
                }

            }
        }

        classBuffer.append("\n");
        classBuffer.append("}");
        classBuffer.append("\n");

        String classString = classBuffer.toString();

        Map<String, String> importClassMap = ImportClassMap.value;
        for (String str : importClassMap.keySet()) {
            if (classString.contains(str)) {
                importClassList.add(importClassMap.get(str));
            }
        }


        for (int i = 0; i < importClassList.size(); i++) {
            String javaImportClass =  importClassList.get(i);
            importBuffer.append("import ").append(javaImportClass).append(";").append("\n");
        }

        classFile.append(packageBuffer.toString()).append("\n");

        String importString = importBuffer.toString();
        if (StringUtils.isNotBlank(importString)) {
            classFile.append(importString).append("\n");
        }


        classFile.append(classBuffer);

        return classFile.toString();
    }


}